// Set service path
window.softools = {};
window.softools.servicePath = "https://api.softools.net/";
window.softools.tenant = "demo";
window.softools.token = "";

// Set default headers
var setXhrHeaders = function (jqxhr) {
    jqxhr.setRequestHeader("Cache-Control", "no-transform");
    jqxhr.setRequestHeader("X-Softools-Tenant", window.softools.tenant);
    jqxhr.setRequestHeader("Authorization", "Bearer " + window.softools.token);
    jqxhr.setRequestHeader("Content-Type", "application/json");
    jqxhr.setRequestHeader("Accept", "application/json");
}

// Generic function to handle AJAX errors
var handleAjaxError = function (jqxhr, textStatus, errorThrown) {
    if (jqxhr.readyState == 0 || jqxhr.status == 0) {
        return; //Skip this error
    }
    if (jqxhr.status == 401) {
        alert('Not Authorised');
        return;
    }
    if (jqxhr.status == 400) {
        //Chances are that this is due to validation
        return;
    } else {
        try {
            var error = JSON.parse(jqxhr.responseText);
            var displayText = error.Message;
            if (error.ExceptionMessage && error.ExceptionMessage != error.Message) {
                displayText = displayText + " - " + error.ExceptionMessage;
            }
            alert(displayText);
        } catch (e) {
            var displayText = "An unexpected error occurred - " + errorThrown;
            alert(displayText);
        }
    }
}

// Append headers to all requests
$(document).ajaxSend(function (event, jqxhr, settings) {
    setXhrHeaders(jqxhr);
});


$.support.cors = true;

function appsViewModel() {

    var self = this;

    self.getApps = function () {
        var url = window.softools.servicePath + "api/apps";
		
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {

		//var arr = JSON.parse(data);
		var i;
    var out = "<table>";
	
	 for(i = 0; i < data.length; i++) {
        out += "<tr><td>" + 
		"<img src='briefcase.png'/></td><td style='padding-top: 12px; -moz-padding-start:10px;'><a href="+url+"/"+data[i].Id +">" +
        data[i].Title +
        "</a></td></tr>";
    }
    out += "</table>"
	//alert(out);
    document.getElementById("id01").innerHTML = out;
		 self.apps = ko.observableArray([data]);
		    self.apps(ko.mapping.fromJS(data)());
			
        });
    };
	
	    self.getSubApps = function () {
        var url = window.softools.servicePath + "api/apps";
		
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {

		//var arr = JSON.parse(data);
		var i;
    var out = "<table>";
	
	 for(i = 0; i < data.length; i++) {
        out += "<tr><td>" + 
		"<img src='briefcase.png'/></td><td style='padding-top: 12px; -moz-padding-start:10px;'><a href="+url+"/"+data[i].Id +">" +
        data[i].Title +
        "</a></td></tr>";
    }
    out += "</table>"
	//alert(out);
    document.getElementById("id01").innerHTML = out;
		 self.apps = ko.observableArray([data]);
		    self.apps(ko.mapping.fromJS(data)());
			
        });
    };

}

$(document).ready(function () {
    // Auth request
	
    var authRequest = function (username, password) {
        var url = window.softools.servicePath + "token";

        var auth = {
            grant_type: "password",
            username: window.softools.tenant + "\\" + username,
            password: password
        };

        return $.ajax(url, {
            type: "POST",
            global: false,
            data: auth,
            beforeSend: function (jqxhr) {
                jqxhr.setRequestHeader("Accept", "application/json");
            }
        }).done(function (data) {
            window.softools.token = data.access_token;
			
            return true;
        }).fail(function (jqxhr, textStatus, errorThrown) {
            handleAjaxError(jqxhr, textStatus, errorThrown);
            return false;
        });
    }

    authRequest("\jacka", "sunshine1234").then(function (result) {
        var model = new appsViewModel();
		model.getSubApps();
        
		ko.applyBindings(model);
		
    });
});